<template>
  <div id="webgl"></div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import * as THREE from "three";
import earth_img from "../assets/PerspectiveCamera.png";
import poly_haven_studio_4k_hdr from "../assets/poly_haven_studio_4k.hdr";

// 创建3D场景对象Scene
const scene = new THREE.Scene();
//创建一个长方体几何对象Geometry
const geometry = new THREE.PlaneGeometry(1, 1); //长方体
//纹理贴图加载器TextureLoader
const texLoader = new THREE.TextureLoader();
// .load()方法加载图像，返回一个纹理对象Texture
const texture = texLoader.load(earth_img);
texture.colorSpace = THREE.SRGBColorSpace;

// 场景
const rgbeLoader = new RGBELoader();
rgbeLoader.load(poly_haven_studio_4k_hdr, function (envMap) {
  envMap.mapping = THREE.EquirectangularReflectionMapping;
  scene.background = envMap;
  scene.environment = envMap;
});

// aoMap贴图
// alphaMap贴图
// lightMap贴图
// envMap贴图
const planeGeometry = new THREE.PlaneGeometry(1, 1);
const planeMaterial = new THREE.MeshBasicMaterial({
  color: 0xffffff,
  map: texture,
  transparent: true,
  side: THREE.DoubleSide,
});
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
scene.add(plane);

const gui = new GUI();
gui
  .add(texture, "colorSpace", {
    sRGB: THREE.SRGBColorSpace,
    Linear: THREE.LinearSRGBColorSpace,
  })
  .onChange(() => {
    texture.needsUpdate = true;
  });

// 定义threejs输出画布的尺寸(单位:像素px)
const width = window.innerWidth; //宽度
const height = window.innerHeight; //高度
// 实例化一个透视投影相机对象
const camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
//相机在Three.js三维坐标系中的位置
// 根据需要设置相机位置具体值
camera.position.set(0, 0, 10);
//相机观察目标指向Threejs 3D空间中某个位置
camera.lookAt(plane.position); //指向mesh对应的位置

// AxesHelper：辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(150);
scene.add(axesHelper);

// 创建渲染器对象
const renderer = new THREE.WebGLRenderer();

renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
renderer.setClearColor(0xffffff, 1);
renderer.render(scene, camera);

// 设置相机控件轨道控制器OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
// 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
controls.addEventListener("change", function () {
  renderer.render(scene, camera); //执行渲染操作
}); //监听鼠标、键盘事件

function render() {
  renderer.render(scene, camera); //执行渲染操作
  requestAnimationFrame(render);
}
render();

onMounted(() => {
  document.getElementById("webgl").appendChild(renderer.domElement);
});
</script>
